package com.fg.cloud.agency.controller.system;

import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.fg.cloud.agency.controller.BaseAgencyController;
import com.fg.cloud.common.PageUtils;
import com.fg.cloud.common.StatusCode;
import com.fg.cloud.common.encrypt.Encrypt;
import com.fg.cloud.common.finals.Agency;
import com.fg.cloud.common.finals.UserType;
import com.fg.cloud.common.message.AliyunSMS;
import com.fg.cloud.common.quantity.ResultType;
import com.fg.cloud.common.shiro.UserUtils;
import com.fg.cloud.common.validate.LongUtils;
import com.fg.cloud.manager.entry.agency.AgencyAddressEntity;
import com.fg.cloud.manager.entry.agency.AgencyEntity;
import com.fg.cloud.manager.entry.agency.AgencyImagesEntity;
import com.fg.cloud.manager.entry.agency.vo.AgencyAddressVo;
import com.fg.cloud.manager.entry.agency.vo.AgencyInfoVo;
import com.fg.cloud.manager.entry.agency.vo.AgencyInvoiceVo;
import com.fg.cloud.manager.entry.agency.vo.AgencyUserVo;
import com.fg.cloud.manager.entry.agency.vo.AgencyVo;
import com.fg.cloud.manager.service.agency.AgencyAddressService;
import com.fg.cloud.manager.service.agency.AgencyInfoService;
import com.fg.cloud.manager.service.agency.AgencyService;
import com.fg.cloud.manager.service.agency.AgencyUserService;

/**
 * Description:经销商个人信息管理
 * @author dingjiang
 * @date 2017年8月21日上午9:13:02
 */
@Controller
@RequestMapping("/agencyInfo")
public class AgencyInfoController extends BaseAgencyController {
	
	@Autowired
	private AgencyInfoService agencyInfoService;
	@Autowired
	private AgencyService agencyService;
	@Autowired
	private AgencyAddressService agencyAddressService;
	@Autowired
	private AgencyUserService agencyUserService;

	/**
	 * Description:查询当前经销商的个人信息
	 * @param req
	 * @param resp
	 * @author dingjiang
	 * @date 2017年8月21日下午1:18:44
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping("/selectInfo")
	@ResponseBody
	public void selectInfo(HttpServletRequest req, HttpServletResponse resp) {
		try {
			AgencyInfoVo result = agencyInfoService.selectAgencyInfo(getCurrentAgencyUser().getId(), 
					getCurrentAgencyUser().getFacId(), getCurrentAgencyUser().getAgeId());
			if (null != result) {				
				doResult(resp, true, StatusCode.FINDSUCCESS, result, ResultType.FIND_SUCCESS);
			} else {
				doResult(resp, false, StatusCode.FINDERROR, null, ResultType.FIND_NULL);
			}
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.FINDERROR, null, e.getMessage());
		}
	}
	
	/**
	 * Description:保存当前经销商的个人信息
	 * @param req
	 * @param resp
	 * @param agencyUserVo
	 * @author dingjiang
	 * @date 2017年8月21日下午3:13:09
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping("/saveInfo")
	@ResponseBody
	public void saveInfo(HttpServletRequest req, HttpServletResponse resp, AgencyInfoVo agencyUserVo) {
		try {
			agencyUserVo.setId(getCurrentAgencyUser().getId());
			agencyUserVo.setAgeId(getCurrentAgencyUser().getAgeId());
			agencyUserVo.setUpdater(getCurrentAgencyUser().getId());
			agencyInfoService.saveAgencyInfo(agencyUserVo);
			doResult(resp, true, StatusCode.SAVESUCCESS, null, ResultType.SAVE_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.SAVEERROR, null, e.getMessage());
		}
	}
	
	/**
	 * Description:查询发票信息
	 * @param req
	 * @param resp
	 * @author dingjiang
	 * @date 2017年8月21日下午4:33:09
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping("/selectInvoice")
	@ResponseBody
	public void selectInvoice(HttpServletRequest req, HttpServletResponse resp) {
		try {
			AgencyInvoiceVo result = agencyService.finds(getCurrentAgencyUser().getAgeId());
			if (null != result) {
				doResult(resp, true, StatusCode.FINDSUCCESS, result, ResultType.FIND_SUCCESS);
			} else {
				doResult(resp, false, StatusCode.FINDERROR, null, ResultType.FIND_NULL);
			}	
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.FINDERROR, null, e.getMessage());
		}
	}
	
	/**
	 * Description:删除税务图册
	 * @param req
	 * @param resp
	 * @param picUrl
	 * @author dingjiang
	 * @date 2017年8月28日下午6:03:33
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping("/deleteImgs")
	@ResponseBody
	public void deleteImgs(HttpServletRequest req, HttpServletResponse resp, String picUrl){
		try {
			boolean flag = agencyService.deleteImgs(getCurrentAgencyUser().getAgeId(), picUrl);
			if (flag) {
				doResult(resp, flag, StatusCode.REMOVESUCCESS, null, ResultType.REMOVE_SUCCESS);
			} else {
				doResult(resp, flag, StatusCode.REMOVEERROR, null, ResultType.REMOVE_FAULT);
				return ;
			}
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.REMOVEERROR, null, e.getMessage());
		}
	}
	
	/**
	 * Description:新增税务图册
	 * @param req
	 * @param resp
	 * @param picUrl
	 * @author dingjiang
	 * @date 2017年8月28日下午6:32:22
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping("/addImgs")
	@ResponseBody
	public void addImgs(HttpServletRequest req, HttpServletResponse resp, String picUrl){
		try {
			if (StringUtils.isEmpty(picUrl)) {
				doResult(resp, false, StatusCode.SAVEERROR, null, ResultType.INPUT_NULL);
				return ;
			}
			AgencyImagesEntity images = new AgencyImagesEntity();
			images.setAgencyId(getCurrentAgencyUser().getAgeId());
			images.setPicUrl(picUrl);
			/*images.setSeq(1);*/
			boolean flag = agencyService.addImgs(images);
			doResult(resp, flag, flag ? StatusCode.SAVESUCCESS : StatusCode.SAVEERROR, null, 
					flag ? ResultType.SAVE_SUCCESS : ResultType.SAVE_FAULT);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.SAVEERROR, null, e.getMessage());
		}
	}
	
	
	
	/**
	 * Description:保存发票信息
	 * @param req
	 * @param resp
	 * @param agencyEntity
	 * @author dingjiang
	 * @date 2017年8月21日下午4:33:56
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping("/saveInvoice")
	@ResponseBody
	public void saveInvoice(HttpServletRequest req, HttpServletResponse resp, 
			@Param("agencyEntity")AgencyEntity agencyEntity) {
		try {
			agencyEntity.setFacId(getCurrentAgencyUser().getFacId());
			agencyEntity.setId(getCurrentAgencyUser().getAgeId());
			agencyService.updateByPrimaryKeySelective(agencyEntity);
			doResult(resp, true, StatusCode.SAVESUCCESS, null, ResultType.SAVE_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.SAVEERROR, null, e.getMessage());
		}
	}
	
	/**
	 * Description:新增收货地址
	 * @param req
	 * @param resp
	 * @param address
	 * @author dingjiang
	 * @date 2017年8月22日上午9:58:30
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping("/insertAdd")
	@ResponseBody
	public void insertAdd(HttpServletRequest req, HttpServletResponse resp, AgencyAddressVo address) {
		try {
			AgencyUserVo user = getCurrentAgencyUser();
			//判断是否允许修改收货地址
			if ( agencyService.find(getCurrentAgencyUser().getAgeId()).getAddressStatus() == Agency.FAILURE ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "地址不允许修改");
				return ;
			}
			//验证参数非空
			if ( null==address.getCusName() || StringUtils.isEmpty(address.getCusName()) ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "请填写客户名称");
				return ;
			}
			if ( null==address.getReceiver() || StringUtils.isEmpty(address.getReceiver()) ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "请填写收货人");
				return ;
			}
			if ( null==address.getAdministrative() || StringUtils.isEmpty(address.getAdministrative()) ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "请选择省市区");
				return ;
			}
			if ( null==address.getAddress() || StringUtils.isEmpty(address.getAddress()) ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "请填写详细地址");
				return ;
			}
			if ( null==address.getPhone() || StringUtils.isEmpty(address.getPhone()) ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "请填写联系电话");
				return ;
			}
			//判重 
			address.setAgeId( user.getAgeId() );
			if ( agencyAddressService.judgeIsExit(address) ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "该地址已存在");
				return ;
			}
			boolean flag = agencyAddressService.insertAdd(address, user);
			doResult(resp, flag, flag ? StatusCode.SAVESUCCESS : StatusCode.SAVEERROR, null, 
					flag ? ResultType.SAVE_SUCCESS : ResultType.SAVE_FAULT);		
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.SAVEERROR, null, e.getMessage());
		}
	}
	
	
	
	/**
	 * Description:保存收货地址
	 * @param req
	 * @param resp
	 * @param address
	 * @author dingjiang
	 * @date 2017年8月30日下午2:40:57
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping("/saveAdd")
	@ResponseBody
	public void saveAdd(HttpServletRequest req, HttpServletResponse resp, AgencyAddressVo address) {
		try {
			AgencyUserVo user = getCurrentAgencyUser();
			//判断是否允许修改收货地址
			AgencyVo find = agencyService.find( getCurrentAgencyUser().getAgeId() );
			if ( find.getAddressStatus() == Agency.FAILURE ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "地址不允许修改");
				return ;
			}
			//验证ID非空
			if ( LongUtils.isEmpty(address.getId()) ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "ID不能为空！");
				return ;
			}
			//验证ID合法
			AgencyAddressEntity findOne = agencyAddressService.findOne(address.getId(), getCurrentAgencyUser().getAgeId());
			if ( null == findOne  ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "ID输入有误！");
				return ;
			}
			//判重,除了自己以外
			address.setAgeId(getCurrentAgencyUser().getAgeId());
			if ( agencyAddressService.JudgeIsExit(address) ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "该地址已存在");
				return ;
			}
			boolean flag = agencyAddressService.saveAdd(address, user, findOne);
			doResult(resp, flag, flag ? StatusCode.SAVESUCCESS : StatusCode.SAVEERROR, null, 
					flag ? ResultType.SAVE_SUCCESS : ResultType.SAVE_FAULT);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.SAVEERROR, null, e.getMessage());
		}
	}
	
	/**
	 * Description:设置默认收货地址
	 * @param req
	 * @param resp
	 * @param id
	 * @author dingjiang
	 * @date 2017年8月22日下午2:45:23
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value="/setAsdefault",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void setAsdefault(HttpServletRequest req , HttpServletResponse resp , Long id){
		try {
			AgencyAddressVo address = new AgencyAddressVo();
			AgencyUserVo user = getCurrentAgencyUser();
			//判断是否允许修改收货地址
			if ( agencyService.find( user.getAgeId() ).getAddressStatus() == Agency.FAILURE ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "地址不允许修改");
				return ;
			}
			//验证参数非空
			if ( LongUtils.isEmpty( id ) ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, ResultType.INPUT_NULL);
				return ;
			}
			//验证参数合法
			if ( !agencyAddressService.finds( id, user.getAgeId() ) ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "ID输入有误！");
				return ;
			}
			address.setIsDefault(1);
			address.setAgeId( user.getAgeId() );
			address.setId( id );
			address.setUpdater(user.getId());
			boolean flag = agencyAddressService.updateByPrimaryKeySelective(address);
			doResult(resp, flag, flag ? StatusCode.SAVESUCCESS : StatusCode.SAVEERROR, null, 
					flag ? ResultType.SAVE_SUCCESS : ResultType.SAVE_FAULT);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.SAVEERROR, null, e.getMessage());
		}
	}
	
	/**
	 * Description:查询默认收货地址
	 * @param req
	 * @param resp
	 * @author dingjiang
	 * @date 2017年9月27日上午11:14:49
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value="/selectDefault",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void selectDefault(HttpServletRequest req, HttpServletResponse resp){
		try {
			Long ageId = getCurrentAgencyUser().getAgeId();
			AgencyAddressEntity address = agencyAddressService.selectDefault(ageId);
			doResult(resp, address != null ? true : false , address != null ? StatusCode.FINDSUCCESS : StatusCode.FINDERROR, 
					address != null ? address : null, address != null ? ResultType.FIND_SUCCESS : ResultType.FIND_NULL);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.FINDERROR, null, e.getMessage());
		}
	}
	
	
	/**
	 * Description:查询收货地址
	 * @param req
	 * @param resp
	 * @param page
	 * @param rows
	 * @param sort
	 * @param order
	 * @author dingjiang
	 * @date 2017年8月22日上午10:43:05
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value="/selectpage",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void selectPage(HttpServletRequest req, HttpServletResponse resp,
			Integer page, Integer rows, String sort, String order){
		try {
			if (null == page) page = 1;
			if (null == rows) rows = 10;
			PageUtils<AgencyAddressEntity> pageinfo = new PageUtils<AgencyAddressEntity>(page, rows, sort, order);
			pageinfo.getCondition().put("ageId = ", getCurrentAgencyUser().getAgeId());
			agencyAddressService.selectforPage(pageinfo);
			doResult(resp, true, StatusCode.FINDSUCCESS, pageinfo, ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.FINDERROR, null, e.getMessage());
		}
	}
	
	/**
	 * Description:删除收货地址(物理删除，没毛病)
	 * @param req
	 * @param resp
	 * @param ids
	 * @author dingjiang
	 * @date 2017年8月22日下午1:27:46
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value="/delete",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void delete(HttpServletRequest req , HttpServletResponse resp , @Param("ids")String ids){
		try {
			if (StringUtils.isEmpty(ids)) {
				doResult(resp, false, StatusCode.SAVEERROR, null, ResultType.INPUT_NULL);
				return ;
			}
			String[] strs = ids.split(",");
			Long[] arrays = new Long[strs.length];
			for(int i = 0; i < strs.length; i++){
				arrays[i] = Long.parseLong(strs[i]);
		    }
			agencyAddressService.remove(getCurrentAgencyUser().getAgeId(),arrays);
			doResult(resp, true, StatusCode.REMOVESUCCESS, null, ResultType.REMOVE_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.REMOVEERROR, null, ResultType.REMOVE_FAULT);
		}
	}
	
	/**
	 * Description:获取短信验证码
	 * @param req
	 * @param resp
	 * @author dingjiang
	 * @date 2017年9月14日下午8:00:36
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value="/validateCode",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void validateCode( HttpServletRequest req, HttpServletResponse resp, String mobile ){
		try {
			String templateCode = "SMS_95785030";
			Random random = new Random();
			String templateParam = String.valueOf(random.nextInt(10000));		
			AliyunSMS.sendSMS(templateCode, mobile, templateParam);
			//短信验证码
			req.getSession().setAttribute("sendMsg", templateParam);
			doResult(resp, true, StatusCode.SAVESUCCESS, templateParam, "发送成功！");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Description:修改当前用户密码
	 * @param req
	 * @param resp
	 * @param oldPsd
	 * @param newPsd
	 * @param renewPsd
	 * @author dingjiang
	 * @date 2017年8月22日下午3:37:28
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value="/modifyPsd",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public void modifyPsd(HttpServletRequest req , HttpServletResponse resp , String oldPsd , 
			String newPsd , String renewPsd){
		try {
			//验证码验证
			/*if ( StringUtils.isEmpty(validateCode) ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "验证码不能为空！");
				return ;
			}
			String sendMsg = (String)req.getSession().getAttribute("sendMsg");
			if ( !validateCode.equals(sendMsg) ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "验证码输入有误！");
				return ;
			}*/
			//验证参数非空
			if ( null == oldPsd || StringUtils.isEmpty(oldPsd) ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "旧密码不能为空");
				return ;
			}
			if ( null == newPsd || StringUtils.isEmpty(newPsd) ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "新密码不能为空");
				return ;
			}
			if ( null == renewPsd || StringUtils.isEmpty(renewPsd) ) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "确认密码不能为空");
				return ;
			}
			if (!newPsd.equals(renewPsd)) {
				doResult(resp, false, StatusCode.SAVEERROR, null, "两次密码输入不一致");
				return ;
			}
			boolean flag = agencyUserService.resetPassword( getCurrentAgencyUser().getId(), Encrypt.md5(oldPsd), Encrypt.md5(newPsd) );
			if (flag) {
				doResult(resp, true, StatusCode.SAVESUCCESS, null, ResultType.SAVE_SUCCESS);
			} else {
				doResult(resp, false, StatusCode.SAVEERROR, null, "旧密码输入有误");
				return ;
			}
			//密码修改成功后清除用户信息，退出当前用户，前端跳转至登录界面
			UserUtils.clearCachedAuthorizationInfo();
		} catch (Exception e) {
			e.printStackTrace();
			doResult(resp, false, StatusCode.SAVEERROR, null, e.getMessage());
		}
	}
	
	
	
}
